//
//  DetailViewController.m
//  MGSplitView
//
//  Created by Gonzalo Gonzalez on 10/11/2012.
//

/*
 Copyright (C) 2014, ownCloud, Inc.
 This code is covered by the GNU Public License Version 3.
 For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/
 You should have received a copy of this license
 along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.en.html>.
 */

#import "DetailViewController.h"

#import "AppDelegate.h"
#import "MainPopOverBarckground.h"
#import "UIColor+Constants.h"
#import "constants.h"
#import "EditAccountViewController.h"
#import "UtilsDtos.h"
#import "UIImage+Resize.h"
#import "FileNameUtils.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "Customization.h"
#import "ManageFilesDB.h"
#import "FilesViewController.h"
#import "UploadUtils.h"
#import "OCNavigationController.h"
#import "UIAlertView+Blocks.h"
#import "ShareFileOrFolder.h"
#import "OCCommunication.h"
#import "OCErrorMsg.h"
#import "ManageFavorites.h"
#import "SettingsViewController.h"
#import "UtilsUrls.h"


NSString * IpadFilePreviewViewControllerFileWasDeletedNotification = @"IpadFilePreviewViewControllerFileWasDeletedNotification";
NSString * IpadFilePreviewViewControllerFileWasDownloadNotification = @"IpadFilePreviewViewControllerFileWasDownloadNotification";
NSString * IpadFilePreviewViewControllerFileWhileDonwloadingNotification = @"IpadFilePreviewViewControllerFileWhileDonwloadingNotification";
NSString * IpadFilePreviewViewControllerFileFinishDownloadNotification = @"IpadFilePreviewViewControllerFileFinishDownloadNotification";
NSString * IpadSelectRowInFileListNotification = @"IpadSelectRowInFileListNotification";
NSString * IpadCleanPreviewNotification = @"IpadCleanPreviewNotification";
NSString * IpadShowNotConnectionWithServerMessageNotification = @"IpadShowNotConnectionWithServerMessageNotification";



@interface DetailViewController ()

- (void)configureView;

@end


@implementation DetailViewController

@synthesize splitController, popoverController, toolbar;


#pragma mark - Load view methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //Enable toolBar
    [toolbar setUserInteractionEnabled:YES];
    
    
    //Init global atributes
    _progressView.progress=0.0;
    _progressView.hidden=YES;
    _cancelButton.hidden=YES;
    _progressLabel.hidden=YES;
    _previewImageView.hidden=YES;
    _isDownloading=NO;
    _isViewBlocked=NO;
    _isExtend=NO;
    _isExtending=NO;
    _isFileCharged=NO;
    _disablePopover=NO;
    _isOverwritedFile=NO;
    _isUpdatingFile = NO;
    _controllerManager = noManagerController;
    
    //Init notificacion in status bar
    _notification = [CWStatusBarNotification new];
    _updatingFileView.hidden = YES;
   
    //MainScroll View autoresizing
    [_mainScrollView setTranslatesAutoresizingMaskIntoConstraints:YES];
   
    self.edgesForExtendedLayout = UIRectCornerAllCorners;
    
    //Bar items. Set to botom in iOS 7
    [_toggleItem setImageInsets:UIEdgeInsetsMake(10, 0, -10, 0)];
    [_openButtonBar setImageInsets:UIEdgeInsetsMake(10, 0, -10, 0)];
    [_favoriteButtonBar setImageInsets:UIEdgeInsetsMake(10, 0, -10, 0)];
    [_shareLinkButtonBar setImageInsets:UIEdgeInsetsMake(10, 0, -10, 0)];
    [_deleteButtonBar setImageInsets:UIEdgeInsetsMake(10, 0, -10, 0)];
    
    //Set Constraints
    _toolBarHeightConstraint.constant=64;
    _topMarginTitleLabelConstraint.constant=32;
    _progressViewHeightConstraint.constant=2;
    _fileTypeCenterHeightConstraint.constant=-40;
    

    //Set title and the font of the label of the toolBar
    [_titleLabel setFont:[UIFont systemFontOfSize:18.0]];
    [_titleLabel setText:@""];
    
    //Set color of background
    self.view.backgroundColor = [UIColor colorOfBackgroundDetailViewiPad];
    
    //Set notifications for communication betweenViews
    [self setNotificationForCommunicationBetweenViews];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //Show popover when the screen is loaded
    [self showPopover];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    _isViewBlocked = NO;
    _isCancelDownloadClicked = NO;
    //Configure view
    [self configureView];
}

/*
 * Method that show or not show popover in this cases:
 * Automatic show popover in potrait view
 * Not show popover in landscape view
 * Not show popover in potrait view when the app receive a file from other app.
 * Not show popover in potrait or landscape extend if the player is in full screen option.
 */
-(void) showPopover {
    
    DLog(@"show popover");
    
    UIInterfaceOrientation currentOrientation;
    currentOrientation=[[UIApplication sharedApplication] statusBarOrientation];
    BOOL isPotrait = UIDeviceOrientationIsPortrait(currentOrientation);
    BOOL disableAutomaticPopover=NO;
    //If is player in fullscreen running not show popover automatic
    if (_moviePlayer) {
        if (_moviePlayer.isFullScreen) {
            disableAutomaticPopover=YES;
        }
    }
    
    if (_disablePopover) {
        disableAutomaticPopover=YES;
    }
    
    //Disable automatic popover if the player is in full screen
    if (disableAutomaticPopover==NO) {
        
        if (isPotrait==YES) {
            
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
            
            //Method that show popover automatic if app dont show from other app
            if (appDelegate.isSharedToOwncloudPresent == NO && appDelegate.isPasscodeVisible == NO && appDelegate.isSharedToOwncloudPresent == NO && appDelegate.settingsViewController.isMailComposeVisible == NO) {

                if (self.popoverController!=nil && self.view.window != nil) {
                    DLog(@"Popover exist");
                    UIBarButtonItem *item = [toolbar.items objectAtIndex:0];
                    [self.popoverController presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
                }
            } else {
                if ([self.popoverController isPopoverVisible]) {
                    [self.popoverController dismissPopoverAnimated:NO];
                }
            }
        } else {
            
            //Method that show popover automatic
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
            if (appDelegate.isSharedToOwncloudPresent == NO && _isExtending == NO) {
                if (self.popoverController!=nil && self.view.window != nil) {
                    DLog(@"Popover exist");
                    UIBarButtonItem *item = [toolbar.items objectAtIndex:0];
                    [self.popoverController presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
                }
            } else {
                _isExtending = NO;
                if ([popoverController isPopoverVisible]) {
                    [popoverController dismissPopoverAnimated:NO];
                }
            }
        }
    }
}

/*
 *Method taht close popover if this is visible
 */
-(void)closePopover{
    
    if (popoverController.isPopoverVisible) {
        [popoverController dismissPopoverAnimated:NO];
    }
}

- (void)configureView
{
    DLog(@"Detail Configure view");
    
    UIInterfaceOrientation currentOrientation;
    currentOrientation=[[UIApplication sharedApplication] statusBarOrientation];
    BOOL isPotrait = UIDeviceOrientationIsPortrait(currentOrientation);
    
    //Set the content offset of the gallery view scroll view.
    if (_galleryView) {
        [_mainScrollView setContentOffset:_mainScrollView.contentOffset animated:YES];
        [_galleryView.scrollView setContentOffset:_mainScrollView.contentOffset animated:YES];
    }
    
    //TitleLabel
    if (_file) {
        [_titleLabel setText:[_file.fileName stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]];
    } else if (_isFileCharged==NO && _file==nil){
        [_titleLabel setText:_linkTitle];
    } else {
        [_titleLabel setText:@""];
    }
    
    //Favorite
    [self putTheFavoriteStatus];
    
    //Managed potrait or landscape orientation screen
    if (isPotrait) {
        [self potraitView];
    } else {
        [self landscapeView];
    }
}

#pragma mark - Portrait/Landscape screen

/*
 * Method that manage the interface objects in potrait orientation
 */
-(void)potraitView{
    
    //Configure toolBar
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items removeObject:_toggleItem];
    
    if (_isFileCharged==YES) {
        [items insertObject:_spaceBar atIndex:1];
        [items insertObject:_openButtonBar atIndex:2];
        [items insertObject:_spaceBar1 atIndex:3];
        [items insertObject:_favoriteButtonBar atIndex:4];
        [items insertObject:_spaceBar2 atIndex:5];
        [items insertObject:_shareLinkButtonBar atIndex:6];
        [items insertObject:_spaceBar3 atIndex:7];
        [items insertObject:_deleteButtonBar atIndex:8];
    } else {
        [items removeObject:_spaceBar];
        [items removeObject:_openButtonBar];
        [items removeObject:_spaceBar1];
        [items removeObject:_favoriteButtonBar];
        [items removeObject:_spaceBar2];
        [items removeObject:_shareLinkButtonBar];
        [items removeObject:_spaceBar3];
        [items removeObject:_deleteButtonBar];
    }
    
    [toolbar setItems:items animated:YES];
    
    //Configure size of movie player dinamically
    if (_moviePlayer) {
        if (_moviePlayer.isFullScreen==NO) {
            _moviePlayer.moviePlayer.view.frame= _mainScrollView.frame;
        } else {
            CGRect fullScreenFrame = _mainScrollView.frame;
            fullScreenFrame.size.height = _mainScrollView.frame.size.height + toolbar.frame.size.height;
            fullScreenFrame.origin.y = toolbar.frame.origin.y;
            _moviePlayer.moviePlayer.view.frame= fullScreenFrame;
        }
    }
}

/*
 * Method that manage the interface objects in landscape orientation
 */
- (void)landscapeView{
    
    //Configure toolBar
    UIImage *image;
    if ([splitController isShowingMaster]) {
        image = [UIImage imageNamed:@"arrow_button.png"];
    } else {
        image = [UIImage imageNamed:@"conarrow_button.png"];
    }
    
    _toggleItem.image=image;
    _toggleItem.style=UIBarButtonItemStylePlain;
    
    //Diferents configures of tool bar depends if the detail view is extend or not.
    if (_isExtend==YES) {
        
        NSMutableArray *items = [[toolbar items] mutableCopy];
        UIBarButtonItem *popoverItem = [items objectAtIndex:0];
        [items removeAllObjects];
        [items insertObject:popoverItem atIndex:0];
        [items insertObject:_toggleItem atIndex:1];
        [items insertObject:_spaceBar atIndex:2];
        
        if (_isFileCharged==YES) {
            [items insertObject:_openButtonBar atIndex:3];
            [items insertObject:_spaceBar1 atIndex:4];
            [items insertObject:_favoriteButtonBar atIndex:5];
            [items insertObject:_spaceBar2 atIndex:6];
            [items insertObject:_shareLinkButtonBar atIndex:7];
            [items insertObject:_spaceBar3 atIndex:8];
            [items insertObject:_deleteButtonBar atIndex:9];
        }
        
        [toolbar setItems:items animated:YES];
        
        
        //Configure size of movie player dinamically
        if (_moviePlayer) {
            if (_moviePlayer.isFullScreen==NO) {
                _moviePlayer.moviePlayer.view.frame= _mainScrollView.frame;
            } else {
                CGRect fullScreenFrame = _mainScrollView.frame;
                fullScreenFrame.size.height = _mainScrollView.frame.size.height + toolbar.frame.size.height;
                fullScreenFrame.origin.y = toolbar.frame.origin.y;
                _moviePlayer.moviePlayer.view.frame= fullScreenFrame;
            }
        }
        
    } else {
        //Landscape normal mode
        NSMutableArray *items = [[toolbar items] mutableCopy];
        [items removeAllObjects];
        [items insertObject:_toggleItem atIndex:0];
        [items insertObject:_spaceBar atIndex:1];
        
        if (_isFileCharged==YES) {
            [items insertObject:_openButtonBar atIndex:2];
            [items insertObject:_spaceBar1 atIndex:3];
            [items insertObject:_favoriteButtonBar atIndex:4];
            [items insertObject:_spaceBar2 atIndex:5];
            [items insertObject:_shareLinkButtonBar atIndex:6];
            [items insertObject:_spaceBar3 atIndex:7];
            [items insertObject:_deleteButtonBar atIndex:8];
        }
        [toolbar setItems:items animated:YES];
        
        if (_moviePlayer) {
            _moviePlayer.moviePlayer.view.frame= _mainScrollView.frame;
        }
    }
}

#pragma mark - Handle file methods

///-----------------------------------
/// @name Handle File
///-----------------------------------

/**
 * This method is the main of the class to handle a file and send this to the 
 * correct controller
 *
 * @param myFile -> FileDto
 * @param controller -> enum type
 */
- (void) handleFile:(FileDto*)myFile fromController:(NSInteger)controller {
    DLog(@"HandleFile _file.fileName: %@", _file.fileName);
    
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    //Control if managedcontroller is not select
    if (_controllerManager == noManagerController) {
        _controllerManager = controller;
    }
    
    //The file came from other view
    if (_controllerManager != controller) {
        _controllerManager = controller;
        _file = nil;
    } else {
        _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
    }
    
    //Get the current local folder
    _currentLocalFolder = [NSString stringWithFormat:@"%@%d/%@", [UtilsUrls getOwnCloudFilePath],app.activeUser.idUser, [UtilsDtos getDBFilePathOfFileDtoFilePath:myFile.filePath ofUserDto:app.activeUser]];
    _currentLocalFolder = [_currentLocalFolder stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    //Quit the title
    _linkTitle=@"";
    
    //Obtain the type of file
    _typeOfFile = [FileNameUtils checkTheTypeOfFile:myFile.fileName];
    
    
    if ([self isTheSameFile:myFile]) {
        [self manageTheSameFileOnThePreview];
    } else {
        //Stop the notification
        [self stopNotificationUpdatingFile];
        //Put the title in the toolBar
        [_titleLabel setText:[_file.fileName stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]];
        _isViewBlocked = NO;
        
        //Remove the views
        [self removeThePreviousViews];
        
        //Interface attributes for progress download info
        _progressLabel.text = @"";
        _progressView.progress = 0.0;
        _updatingFileProgressView.progress = 0.0;
        
        [self manageDistinctFileOnPreview];
    }
    
    //Set if there is a new version of a favorite file and it's not checked
    if (_file.isFavorite && !_file.isNecessaryUpdate && _file.isDownload == downloaded) {
        [self checkIfThereIsANewFavoriteVersion];
    }
}


///-----------------------------------
/// @name Is the same file
///-----------------------------------

/**
 * This method checks if the file is the same that the previewed
 *
 * @param FileDto > myFile, the file for check
 *
 * @return BOOL > YES, if it is the same file
 * @return BOOL > NO, if it is a different one
 */
- (BOOL) isTheSameFile: (FileDto*)myFile {
    //Check if the file is the same file
    BOOL isTheSameFile = NO;
    
    if (_file && !_isOverwritedFile) {
        if ([_file.localFolder isEqualToString: myFile.localFolder]) {
            //Check if the file is downloaded or not
            if (_file.isDownload == downloaded || _file.isDownload == updating || _file.isDownload == downloading)
                isTheSameFile = YES;
        } else {
            _file=myFile;
            isTheSameFile = NO;
        }
    } else {
        _file=myFile;
        isTheSameFile = NO;
        _isOverwritedFile = NO;
    }
    return isTheSameFile;
}


///-----------------------------------
/// @name manageTheSameFileOnThePreview
///-----------------------------------

/**
 * This method manages the file on the preview when the user taps on the same file which is previewed on the iPad view
 */
- (void) manageTheSameFileOnThePreview {
    
    //If the file is download and pending to be updated
    if (_file.isNecessaryUpdate && _file.isDownload == downloaded) {
        if (_typeOfFile != imageFileType) {
            //Update the file
            [self downloadTheFile];
        } else {
            [self openGalleryFileOnUpdatingProcess:YES];
        }
    } else if (_isUpdatingFile && _typeOfFile == imageFileType) {
        [self openGalleryFileOnUpdatingProcess:NO];
    }
}


///-----------------------------------
/// @name manageDistinctFileOnPreview
///-----------------------------------

/**
 * This method manages the file on the preview when the user taps on a distinct file that is previewed on the iPad view
 */
- (void) manageDistinctFileOnPreview {
    /*Check the file
     *1.- Automatic download file
     *  1.1. Image file (gallery)
     *  1.2. Media file (audio, video)
     *  1.3. Office file (doc, xls, txt, docx...)
     *2.- Manual download file
     *  2.1. Other file types.
     */
    
    if (_typeOfFile == imageFileType) {
        if (_file.isNecessaryUpdate) {
            _isUpdatingFile = YES;
        }
        [self initGallery];
    } else {
        
        [self previewFile];
        _file = [ManageFilesDB getFileDtoByIdFile:_file.idFile];
        DLog(@"ide file: %d",_file.idFile);
        
        //Check if the file is in the device
        if (([_file isDownload] == notDownload) && _typeOfFile != otherFileType) {
            //Download the file
            [self downloadTheFile];
        } else if (([_file isDownload] == downloading) || ([_file isDownload] == updating)) {
            
            if ([_file isDownload] == updating) {
                //Preview the file if the file is on an updating process
                if (_typeOfFile == videoFileType || _typeOfFile == audioFileType) {
                    [self performSelectorOnMainThread:@selector(playMediaFile) withObject:nil waitUntilDone:YES];
                } else if (_typeOfFile == officeFileType) {
                    [self performSelectorOnMainThread:@selector(openFileOffice) withObject:nil waitUntilDone:YES];
                } else {
                    [self cleanViewWithoutBlock];
                }
            }
            
            //Get download object
            AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            NSArray *downs = [appDelegate.downloadManager getDownloads];
            
            __block Download *download = nil;
            
            [downs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                download = (Download*)obj;
                if ([download.fileDto.filePath isEqualToString:_file.filePath] && [download.fileDto.fileName isEqualToString:_file.fileName] && download.fileDto.userId == _file.userId){
                     *stop = YES;
                }
                
            }];
            
            //Check to know if it's in progress
            if ((download && [download.operation isExecuting]) || (download && download.downloadTask && download.downloadTask.state == NSURLSessionTaskStateRunning) ) {
                [self contiueDownloadIfTheFileisDownloading];
            }else{
                [self restartTheDownload];
            }
            
        } else {
            //If the file is downloaded
            [self downloadTheFile];
            
            //Preview the file
            if (_typeOfFile == videoFileType || _typeOfFile == audioFileType) {
                [self performSelectorOnMainThread:@selector(playMediaFile) withObject:nil waitUntilDone:YES];
            } else if (_typeOfFile == officeFileType) {
                [self performSelectorOnMainThread:@selector(openFileOffice) withObject:nil waitUntilDone:YES];
            } else {
                [self cleanViewWithoutBlock];
            }
        }
    }
}


///-----------------------------------
/// @name checkIfThereIsANewFavoriteVersion
///-----------------------------------

/**
 * This method checks if there is on a favorite file a new version on the server
 */
- (void) checkIfThereIsANewFavoriteVersion {
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if([[AppDelegate sharedManageFavorites] thereIsANewVersionAvailableOfThisFile:_file]) {
        //Set the file as isNecessaryUpdate
        [ManageFilesDB setIsNecessaryUpdateOfTheFile:_file.idFile];
        //Update the file on memory
        _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
        [self reloadFileList];
        [self manageTheSameFileOnThePreview];
    }
}

/*
 * Method that execute a image of type of file.
 */

- (void)previewFile {
    _companyImageView.hidden=YES;
    self.view.backgroundColor = [UIColor whiteColor];
    _previewImageView.hidden=NO;
    
    //Get the image preview name
    NSString *filePreviewName = [FileNameUtils getTheNameOfTheImagePreviewOfFileName:_file.fileName];
    _previewImageView.image = [UIImage imageNamed:filePreviewName];
    
    _isFileCharged = YES;
    [self configureView];
}

/*
 * Method than call open with class
 */
- (void)openFile {
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
    
    if (!_openWith) {
        _openWith = [[OpenWith alloc]init];
    }
    //Openwith
    _openWith.parentButton=_openButtonBar;
    [_openWith openWithFile:_file];
    
    _isViewBlocked = NO;
}

/*
 * Method that show a office file in the screen
 */

- (void)openFileOffice{
    
    if (_file.localFolder!=nil) {
        
        if (!_officeView) {
            CGRect frame = _mainScrollView.frame;
            _officeView=[[OfficeFileView alloc]initWithFrame:frame];
        } else {
            [_officeView.webView removeFromSuperview];
        }
        _officeView.delegate = self;
        [_officeView openOfficeFileWithPath:_file.localFolder andFileName:_file.fileName];
        
        [self.view addSubview:_officeView.webView];
        
    }
    _isViewBlocked = NO;
}


///-----------------------------------
/// @name openGalleryFileOnUpdatingProcess
///-----------------------------------

/**
 * This method apen a gallery file on an updating process or not
 *
 * @param isUpdatingProcess -> BOOL, manage if it an updating process
 */
- (void) openGalleryFileOnUpdatingProcess: (BOOL) isUpdatingProcess {
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    _isUpdatingFile = isUpdatingProcess;
    //Update the file
    _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
    
    //Quit the gallery view
    if (_galleryView) {
        [_galleryView.scrollView removeFromSuperview];
        _galleryView = nil;
    }
    //Init the gallery
    [self initGallery];
}


/*
 * Delegate method of the OfficeFileView
 * Indicate that the link is load in the officeFileView
 * and set the name of the link.
 * We use this feature for example to charge Help page.
 */

- (void)finishLinkLoad {
    [_titleLabel setText:_linkTitle];
}

/*
 * Method that open a link in detail view.
 *
 */
- (void) openLink:(NSString*)urlString{
    
    DLog(@"3-Press Help");
    
    DLog(@"Open Link");
    _file = nil;
    _isFileCharged = NO;
    [self presentWhiteView];
    
    if (!_officeView) {
        CGRect frame = self.mainScrollView.frame;
        _officeView=[[OfficeFileView alloc]initWithFrame:frame];
        _officeView.delegate = self;
    } else {
        [_officeView.webView removeFromSuperview];
    }
    
    [_officeView openLinkByPath:urlString];
    
    [self.view addSubview:_officeView.webView];
    
    //Enable view
    _isViewBlocked = NO;
}


#pragma mark - FilesViewController callBacks

/*
 * Method to reload the data of the file list.
 */
- (void)reloadFileList{
    [[NSNotificationCenter defaultCenter] postNotificationName: IpadFilePreviewViewControllerFileWasDownloadNotification object: nil];
}


/*
 * Method to block the file list.
 */
- (void) blockFileList{
    [[NSNotificationCenter defaultCenter] postNotificationName: IpadFilePreviewViewControllerFileWhileDonwloadingNotification object: nil];
}

/*
 * Method to unblock the file list.
 */
- (void) unBlockFileList{
    [[NSNotificationCenter defaultCenter] postNotificationName: IpadFilePreviewViewControllerFileFinishDownloadNotification object: nil];
    
}

/*
 * Method that post a notification that inform to file list or shared view the current selected file in the gallery.
 */
- (void) selectRowInFileList:(FileDto*)fileDto{
    
    [[NSNotificationCenter defaultCenter] postNotificationName: IpadSelectRowInFileListNotification object: fileDto];
    
}

#pragma mark - Delete File Delegate Implementation

- (void)reloadTableFromDataBase
{
    [self unselectCurrentFile];
    [self reloadFileList];
    
    UIInterfaceOrientation currentOrientation;
    currentOrientation=[[UIApplication sharedApplication] statusBarOrientation];
    BOOL isPotrait = UIDeviceOrientationIsPortrait(currentOrientation);
    
    if ((self.popoverController!=nil && self.view.window != nil && isPotrait)||(self.popoverController!=nil && self.view.window != nil && !isPotrait && _isExtend)) {
        DLog(@"Popover exist");
        UIBarButtonItem *item = [toolbar.items objectAtIndex:0];
        [self.popoverController presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
}

- (void)reloadTableAfterDonwload{
    
    [self reloadFileList];
}

//-----------------------------------
/// @name removeSelectedIndexPath
///-----------------------------------

/**
 * Method to remove the selectedPath after delete the file localy
 *
 */

- (void) removeSelectedIndexPath {
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    appDelegate.presentFilesViewController.selectedCell = nil;
}


#pragma mark - Util methods

/*
 * Method that change the name of the toolBar title.
 */
- (void)putTitleInNavBarByName:(NSString *) fileName{
    
    [_titleLabel setText:[fileName stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]];
}


///-----------------------------------
/// @name putTheFavoriteStatus
///-----------------------------------

/**
 * This method puts the favorite star on starred or unstarred state on the preview view
 */
- (void) putTheFavoriteStatus {
    if (_file.isFavorite) {
        //Change the image to unstarred
        _favoriteButtonBar.image = [UIImage imageNamed:@"favoriteTB-filled"];
    } else {
        //Change the image to starred
        _favoriteButtonBar.image = [UIImage imageNamed:@"favoriteTB"];
    }
}


///-----------------------------------
/// @name Put the updated progress bar in the navigation bar
///-----------------------------------

/**
 * This method put the progress bar and the cancel button in the
 * navigation bar instead of the file name
 */
- (void) putUpdateProgressInNavBar {
    _isDownloading = YES;
    DLog(@"Include the progress view in the navigation bar");
    nameFileToUpdate = _file.fileName;
    
    //Constraint in updatingFileProgressView
    _topMarginUpdatingFileProgressView.constant = 10;
    
    _updatingFileView.backgroundColor = [UIColor clearColor];
    _updatingFileView.hidden = NO;
    _titleLabel.hidden = YES;
    _updatingFileProgressView.progress = 0.0;
    
    [_updatingFileView addSubview:_updatingFileProgressView];
    [_updatingFileView addSubview:_updatingCancelButton];
    
    [toolbar addSubview:_updatingFileView];
    
    [self performSelector:@selector(showTextInStatusBar) withObject:nil afterDelay:1.0];
}


///-----------------------------------
/// @name removeThePreviousViews
///-----------------------------------

/**
 * This method removes, if they exist, the previous view of video player, office and gallery view
 */
- (void) removeThePreviousViews {
    //Quit the player if exist
    if (_moviePlayer) {
        [_moviePlayer.moviePlayer.view removeFromSuperview];
    }
    
    //Quit the office view
    if (_officeView) {
        [_officeView.webView removeFromSuperview];
        _officeView = nil;
    }
    
    //Quit the gallery view
    if (_galleryView) {
        [_galleryView.scrollView removeFromSuperview];
        _galleryView = nil;
    }
}

/*
 * Method that presents a white page without option buttons
 */
- (void)presentWhiteView{
    
    _progressView.hidden=YES;
    _cancelButton.hidden=YES;
    _progressLabel.hidden=YES;
    _progressLabel.text=@"";
    _progressView.progress=0.0;
    _mainScrollView.hidden=YES;
    _previewImageView.hidden=YES;
    
    _companyImageView.hidden=NO;
    self.view.backgroundColor = [UIColor colorOfBackgroundDetailViewiPad];
    
    _titleLabel.text=@"";
    
    [_openWith.documentInteractionController dismissMenuAnimated:YES];
    [_mShareFileOrFolder.activityPopoverController dismissPopoverAnimated:YES];
    
    //Quit the movie player and clean memory
    if (_moviePlayer) {
        [_moviePlayer.moviePlayer.view removeFromSuperview];
    }
    
    //Quit the office view and clean memory
    if (_officeView) {
        [_officeView.webView removeFromSuperview];
        _officeView=nil;
    }
    
    //Quit the gallery view and clean memory
    if (_galleryView) {
        [_galleryView.scrollView removeFromSuperview];
        _galleryView=nil;
    }
    
    _isFileCharged=NO;
    _file=nil;
    
    [self configureView];
    
    [self reloadFileList];
    
    [self stopNotificationUpdatingFile];
}

/*
 * Method that show a pop up error from other class
 */
- (void) showErrorOnIpadIfIsNecessaryCancelDownload {
    
    DLog(@"isDownloading: %d", _file.isDownload);
    
    //Call showAlertView in main thread
    [self performSelectorOnMainThread:@selector(showAlertView:)
                           withObject:NSLocalizedString(@"not_possible_connect_to_server", nil)
                        waitUntilDone:YES];
}

/*
 * Method that hidden the preview interface objects and block the screen
 */
- (void)cleanView{
    
    DLog(@"Clean view");
    
    //Clean the view
    //Hidden download elements
    _progressView.hidden=YES;
    _cancelButton.hidden=YES;
    _progressLabel.hidden=YES;
    _progressLabel.text=@"";
    _progressView.progress=0.0;
    
    [toolbar setUserInteractionEnabled:YES];
    _isViewBlocked=YES;
    [self reloadFileList];
}

/*
 *  Method that hidden the preview interface objects
 */

- (void)cleanViewWithoutBlock{
    
    DLog(@"Clean view");
    
    //Clean the view
    //Hidden download elements
    _progressView.hidden=YES;
    _cancelButton.hidden=YES;
    _progressLabel.hidden=YES;
    _progressLabel.text=@"";
    _progressView.progress=0.0;
    
    
    [toolbar setUserInteractionEnabled:YES];
    _isViewBlocked=NO;
    
}

/*
 * Method called from FilesViewController after that unselect a cell and
 * present a white view in detailView
 */
- (void) unselectCurrentFile
{
    DLog(@"unselectCurrentFile");
    
    self.file=[ManageFilesDB getFileDtoByIdFile:self.file.idFile];
    _isFileCharged=NO;
    
    _titleLabel.text=@"";
    _linkTitle=@"";
    
    _isViewBlocked=YES;
    
    self.file=nil;
    
    [self presentWhiteView];
    
    if(_galleryView) {
        [self cleanView];
    }
    
}

#pragma mark - Gallery Methods

/*
 * Open the gallery image
 */
- (void)initGallery{
    
    //Enable user interaction
    _isFileCharged=YES;
    
    [self configureView];
    
    
    if (!_galleryView) {
        _galleryView=[[GalleryView alloc]initWithFrame:_mainScrollView.frame];
        //Pass the current file
        _galleryView.file=_file;
        _galleryView.delegate=self;
        //Init the array of images with the array of files (sort files of file list)
        [_galleryView initArrayOfImagesWithArrayOfFiles:_sortedArray];
        //Init the main scroll view of gallery
        [_galleryView initScrollView];
        //Run the gallery
        [_galleryView initGallery];        
        
    }
    //Add Gallery to the preview
    [self.view addSubview:_galleryView.scrollView];
    
}

#pragma mark - Gallery View Delegate Methods

/*
 * Delegate method that change the file selected from gallery
 */
- (void)selectThisFile:(FileDto*)file{
    
    _file=file;
    
    //Put the name of the file in nav bar
    [self putTitleInNavBarByName:_file.fileName];
    [self putTheFavoriteStatus];
    
    //Inidcate to filelist the selected file
    [self selectRowInFileList:_file];
}


#pragma mark - Action Buttons

/*
 * Open With feature. Action to show the apps that can open the selected file
 */
- (IBAction)didPressOpenWithButton:(id)sender
{
    
    BOOL canOpenButton = NO;
    
    if (_isViewBlocked) {
        //The view is blocked, no actions
        DLog(@"isViewBlocked");
        canOpenButton=NO;
    } else {
        if (_galleryView) {
            if (![_galleryView isCurrentImageDownloading]) {
                canOpenButton=YES;
            } else {
                canOpenButton=NO;
            }
        } else {
            canOpenButton=YES;
        }
    }
    
    if (canOpenButton) {
        
        if ([_mShareFileOrFolder.activityPopoverController isPopoverVisible]) {
            [_mShareFileOrFolder.activityPopoverController dismissPopoverAnimated:YES];
        }
        
        CheckAccessToServer *mCheckAccessToServer = [[CheckAccessToServer alloc] init];
        
        if([_file isDownload]) {
            //This file is in the device
            DLog(@"The file is in the device");
            [self openFile];
        } else  if ([mCheckAccessToServer isNetworkIsReachable]) {
            //File is not in the device
            //Phase 1.1. Download the file
            DLog(@"Download the file");
            Download *download=nil;
            download = [[Download alloc]init];
            download.delegate=self;
            download.currentLocalFolder=_currentLocalFolder;
            
            //View progress view and button
            _progressView.hidden=NO;
            _cancelButton.hidden=NO;
            _progressLabel.text=NSLocalizedString(@"wait_to_download", nil);
            _progressLabel.hidden=NO;
            
            //Block the view
            _isViewBlocked=YES;
            
            [download fileToDownload:_file];
        } else {
            [self downloadFailed:NSLocalizedString(@"not_possible_connect_to_server", nil)andFile:nil];
        }
    }
}

/*
 * Method that launch the share options
 */
- (IBAction)didPressShareLinkButton:(id)sender {
    DLog(@"Share button clicked");
    
    if (_openWith && _openWith.documentInteractionController) {
        [_openWith.documentInteractionController dismissMenuAnimated:YES];
    }
    
    _mShareFileOrFolder = [ShareFileOrFolder new];
    _mShareFileOrFolder.delegate = self;
    _mShareFileOrFolder.viewToShow = self.view;
    _mShareFileOrFolder.parentButton = _shareLinkButtonBar;
    
    _file = [ManageFilesDB getFileDtoByIdFile:_file.idFile];
    [_mShareFileOrFolder showShareActionSheetForFile:_file];
}


/*
 * Method that launch the favorite options
 */
- (IBAction)didPressFavoritesButton:(id)sender {
    //Update the file from the DB
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:appDelegate.activeUser];
    
    if (_file.isFavorite) {
        _file.isFavorite = NO;
        //Change the image to unstarred
        _favoriteButtonBar.image = [UIImage imageNamed:@"favoriteTB"];
    } else {
        _file.isFavorite = YES;
        _isCancelDownloadClicked = NO;
        //Change the image to starred
        _favoriteButtonBar.image = [UIImage imageNamed:@"favoriteTB-filled"];
        //Download the file if it's not downloaded and not pending to be download
        [self downloadTheFileIfIsnotDownloadingInOtherProcess];
    }
    
    //Update the DB
    [ManageFilesDB updateTheFileID:_file.idFile asFavorite:_file.isFavorite];
    [appDelegate.presentFilesViewController reloadTableFromDataBase];
    
    if (_file.isFavorite && _file.isDownload == downloaded) {
        [self checkIfThereIsANewFavoriteVersion];
    }
}

//-----------------------------------
/// @name Download the file if is not downloading
///-----------------------------------

/**
 * We have this method to download the file after a few seconds in order to prevent download the file twice
 *
 */
- (void) downloadTheFileIfIsnotDownloadingInOtherProcess {
    
    if (!_isCancelDownloadClicked) {
        if (_file.isDownload == notDownload) {
            [self downloadTheFile];
        }
    }
}

/*
 * Delete feaure. Action to show a menu to select one delete option of a selected file
 */
- (IBAction)didPressDeleteButton:(id)sender
{
    
    BOOL canOpenButton = NO;
    
    if (_isViewBlocked) {
        //The view is blocked, no actions
        DLog(@"isViewBlocked");
        canOpenButton=NO;
    } else {
        if (_galleryView) {
            if (![_galleryView isCurrentImageDownloading]) {
                canOpenButton = YES;
            } else {
                canOpenButton = NO;
            }
        } else {
            canOpenButton = YES;
        }
    }
    if (canOpenButton) {
        self.mDeleteFile = [[DeleteFile alloc] init];
        self.mDeleteFile.delegate = self;
        self.mDeleteFile.viewToShow = self.view;
        
        DLog(@"idFile: %d", _file.idFile);
        DLog(@"fileName: %@", _file.fileName);
        
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        //Update the file
        _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:appDelegate.activeUser];
        
        DLog(@"idFile: %d", _file.idFile);
        
        [self.mDeleteFile askToDeleteFileByFileDto:self.file];
    }
}

/*
 * Cancel download feature. Action to cancel the download of a selected file.
 */
- (IBAction)didPressCancelButton:(id)sender{
    
    if (_isDownloading) {
        
        _isCancelDownloadClicked = YES;
        
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        NSArray *downs = [appDelegate.downloadManager getDownloads];
        
        Download *download;
        
        for (download in downs) {
             if ([download.fileDto.localFolder isEqualToString: _file.localFolder]) {
                [download cancelDownload];
                _isDownloading=NO;
            }
        }
        
        //Update fileDto
        _file=[ManageFilesDB getFileDtoByIdFile:_file.idFile];
        
        _progressView.hidden = YES;
        _cancelButton.hidden = YES;
        _progressLabel.hidden = YES;
        _progressLabel.text = @"";
        _progressView.progress = 0.0;
    }
    
    _isViewBlocked = NO;
    [self unBlockFileList];
}



///-----------------------------------
/// @name Action of updating cancel button
///-----------------------------------

/**
 * This method handle the updating cancel button
 *
 * @param sender
 */
- (IBAction)didPressUpdatingCancelButton:(id)sender {
    DLog(@"didPressUpdatingCancelButton");
    [self cancelTheUpdating];
}



///-----------------------------------
/// @name Cancel the updating
///-----------------------------------

/**
 * This method cancel the updating process
 */
- (void) cancelTheUpdating {
    DLog(@"cancelTheUpdating");
    if (_isDownloading) {
        
        //Update the download status of the files
        _file.isDownload = downloaded;
        [ManageFilesDB setFileIsDownloadState:_file.idFile andState:downloaded];
        
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        //Copy of the original array
        NSArray *downs = [NSArray arrayWithArray:[appDelegate.downloadManager getDownloads]];
        Download *download;
        BOOL delete;
        for (download in downs) {
            if ([download.fileDto.filePath isEqualToString:_file.filePath] && [download.fileDto.fileName isEqualToString:_file.fileName] && download.fileDto.userId == _file.userId) {
                [download cancelDownload];
                delete = YES;
                _isDownloading = NO;
            }
        }
        //Stop the notification
        [self stopNotificationUpdatingFile];
    }
}



#pragma mark - Media player methods
/*
 * Launch the player for video and audio
 */

- (void)playMediaFile{
    //Control if the popover is open
    if ([self.popoverController isPopoverVisible]==YES) {
        [self.popoverController dismissPopoverAnimated:NO];
    }
    
    //This code is for the streaming case, but not works yet.
    
    /* UserDto *activeUser = [ExecuteManager getActiveUser];
     NSArray *splitedUrl = [activeUser.url componentsSeparatedByString:@"/"];
     
     NSString *serverUrl = [NSString stringWithFormat:@"%@%@%@",[NSString stringWithFormat:@"%@/%@/%@",[splitedUrl objectAtIndex:0],[splitedUrl objectAtIndex:1],[splitedUrl objectAtIndex:2]], _file.filePath, _file.fileName];
     
     DLog(@"remote url: %@", serverUrl);
     
     NSURL *url = [NSURL URLWithString:serverUrl];
     
     NSURLCredential *cred= [NSURLCredential credentialWithUser:activeUser.username password:activeUser.password persistence:NSURLCredentialPersistenceForSession];
     
     NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
     initWithHost: @"192.168.1.162/owncloud/"
     port: 8080
     protocol: @"http"
     realm: serverUrl
     authenticationMethod: NSURLAuthenticationMethodDefault];
     
     [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential: cred forProtectionSpace: protectionSpace];*/
    
    BOOL needNewPlayer = NO;
    if (_file != nil) {
        if (_moviePlayer) {
            DLog(@"Movie urlString: %@", _moviePlayer.urlString);
            DLog(@"File local folder: %@", _file.localFolder);
            if ([_moviePlayer.urlString isEqualToString:_file.localFolder]) {
                needNewPlayer = NO;
            } else {
                [_moviePlayer removeNotificationObservation];
                [_moviePlayer.moviePlayer stop];
                [_moviePlayer finalizePlayer];
                [_moviePlayer.moviePlayer.view removeFromSuperview];
                _moviePlayer = nil;
                /* [[NSNotificationCenter defaultCenter] removeObserver:self
                 name:MPMoviePlayerPlaybackDidFinishNotification
                 object:nil];*/
                needNewPlayer = YES;
            }
        } else {
            needNewPlayer = YES;
        }
        if (needNewPlayer) {
            //If is audio file create a AVAudioSession objetct to enable the music in background
            if (_typeOfFile == audioFileType) {
                NSError *activationError = nil;
                AVAudioSession *mySession = [AVAudioSession sharedInstance];
                [mySession setCategory: AVAudioSessionCategoryPlayback error: &activationError];
                if (activationError) {
                    DLog(@"AVAudioSession activation error: %@", activationError);
                }
                [mySession setActive: YES error: &activationError];
                if (activationError){
                    DLog(@"AVAudioSession activation error: %@", activationError);
                }
            }
            
            NSURL *url = [NSURL fileURLWithPath:_file.localFolder];
            
            _moviePlayer = [[MediaViewController alloc]initWithContentURL:url];
            _moviePlayer.delegate = self;
            _moviePlayer.urlString = _file.localFolder;
            //if is audio file tell the controller the file is music
            _moviePlayer.isMusic=YES;
            AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            appDelegate.mediaPlayer = _moviePlayer;
            
            /* [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(moviePlayBackDidFinish:)
             name:MPMoviePlayerPlaybackDidFinishNotification
             object:nil];      */
            
            _moviePlayer.moviePlayer.controlStyle=MPMovieControlStyleNone;
            
            [_moviePlayer.moviePlayer setFullscreen:NO];
            
            _moviePlayer.moviePlayer.shouldAutoplay=NO;
            
            [self configureView];
            
            [_moviePlayer initHudView];
            
            [_moviePlayer.moviePlayer setScalingMode:MPMovieScalingModeAspectFit];
            [_moviePlayer.moviePlayer prepareToPlay];
            
            [self.view addSubview:_moviePlayer.moviePlayer.view];
            
            [_moviePlayer playFile];
            
            
            
        } else {
            
            [self.view addSubview:_moviePlayer.moviePlayer.view];
        }
    }
}


#pragma mark - Media player delegate methods

/*
 * Delegate method of media player that receive when the user tap the full screen button
 * @isFullScreenPlayer -> Boolean variable that indicate if the user tap over the fullscreen button
 */
- (void)fullScreenPlayer:(BOOL)isFullScreenPlayer{
    
    UIInterfaceOrientation currentOrientation;
    currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    BOOL isLandscape = UIDeviceOrientationIsLandscape(currentOrientation);
    
    if (isFullScreenPlayer) {
        if (isLandscape && !_isExtend) {
            [self toggleMasterView:nil];
            [toolbar setHidden:YES];
            [self configureView];
        } else {
            [toolbar setHidden:YES];
            [self configureView];
        }
    } else {
        
        if (isLandscape && !_isExtend) {
            [self toggleMasterView:nil];
            [toolbar setHidden:NO];
            [self configureView];
        } else {
            [toolbar setHidden:NO];
            [self configureView];
        }
    }
}

#pragma mark - Download Methods


///-----------------------------------
/// @name Restart the download
///-----------------------------------

/**
 * This method restart the download of the current file
 *
 */
- (void) restartTheDownload{
    
    if (([_file isDownload] == downloading) || ([_file isDownload] == updating)) {
        
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        NSArray *downs = [appDelegate.downloadManager getDownloads];
        
        Download *tempDown;
        BOOL downloadIsInProgress = NO;
        //Check if the download is in progress
        for (tempDown in downs) {
            
            if (tempDown.fileDto.idFile == _file.idFile) {
                tempDown.delegate = self;
                downloadIsInProgress = YES;
                break;
            }
        }
        
        if (downloadIsInProgress) {
            
            if ((IS_IOS7 || IS_IOS8) && !k_is_sso_active) {
                
                if (_file.isNecessaryUpdate) {
                    [self putUpdateProgressInNavBar];
                } else {
                    //View progress view and button
                    _progressView.hidden = NO;
                    _cancelButton.hidden = NO;
                    _progressLabel.text = NSLocalizedString(@"wait_to_download", nil);
                    _progressLabel.hidden = NO;
                }
                _isDownloading = YES;
                [tempDown fileToDownload:_file];
                
            }else{
                
                _isDownloading = YES;
                [self didPressCancelButton:nil];
                [self downloadTheFile];
                
            }
        }
        
    }
}


/*
 * Method that continue the download if is in progress or download again if the
 * file is in the downloading database state
 */
- (void) contiueDownloadIfTheFileisDownloading {
    
    if (_file.isDownload == downloading || _file.isDownload == updating) {
        //Find the download in download global array
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        NSArray *downs = [appDelegate.downloadManager getDownloads];
        
        Download *tempDown;
        BOOL downloadIsInProgress = NO;
        //Check if the download is in progress
        for (tempDown in downs) {
            if ([tempDown.fileDto.localFolder isEqualToString: _file.localFolder]) {
                tempDown.delegate = self;
                downloadIsInProgress = YES;
                break;
            }
        }
        if (!downloadIsInProgress) {
            //If the download not is in progress, download again
            
            //Set file like a not download and download again
            [ManageFilesDB setFileIsDownloadState:_file.idFile andState:notDownload];
            
            AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
            
            _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
            
            [self downloadTheFile];
            
        } else {
            if (_file.isDownload == updating) {
                //Show the progress bar and the notification
                [self performSelector:@selector(putUpdateProgressInNavBar) withObject:nil afterDelay:0.3];
            } else {
                //If the download is in progress update de screen objects
                _progressView.hidden = NO;
                
               // DLog(@"progress : %f", _progressView.progress);
                if (_progressView.progress == 0.0) {
                    _progressLabel.text = NSLocalizedString(@"wait_to_download", nil);
                }
                
                _cancelButton.hidden = NO;
                _progressLabel.hidden = NO;
                
                //If is downloadTask suspended
                if (tempDown.downloadTask.state == NSURLSessionTaskStateSuspended) {
                    [appDelegate.downloadManager addDownload:tempDown];
                }
            }
            _isDownloading = YES;
        }
    }
}

/*
 * This method prepare the download manager to download a selected file
 */
- (void)downloadTheFile {
    //0 = not download ; 1 = download ; -1 = downloading
    
    DLog(@"The download state of the file is: %d", _file.isDownload);
    
    if ([_file isDownload]==notDownload || _file.isNecessaryUpdate) {
        //Phase 1.2. If the file isn't in the device, download the file
        Download *download = nil;
        download = [[Download alloc]init];
        download.delegate = self;
        download.currentLocalFolder = _currentLocalFolder;
        
        if (_file.isNecessaryUpdate) {
            [self putUpdateProgressInNavBar];
        } else {
            //Block the view
            _isViewBlocked = YES;
            
            _progressView.hidden = NO;
            _cancelButton.hidden = NO;
            _progressLabel.text = NSLocalizedString(@"wait_to_download", nil);
            _progressLabel.hidden = NO;
        }
        
        _isDownloading = YES;
        [download fileToDownload:_file];
    }
}

/*
 * Method that cancel all current downloads
 */
- (void)cancelAllDownloads{
    
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (app.isSharedToOwncloudPresent==NO) {
        //Cancel all downloads
        [app.downloadManager cancelDownloads];
    }
}



#pragma mark - Download delegate methods

/*
 * This method receive the download progress and set valor to progressView.
 */

- (void)percentageTransfer:(float)percent andFileDto:(FileDto*)fileDto{
    
    if ([fileDto.localFolder isEqualToString: _file.localFolder]) {
        if (_file.isNecessaryUpdate) {
            _updatingFileProgressView.progress = percent;
        } else {
            _progressView.progress = percent;
        }
        DLog(@"PERCENT OF DOWNLOAD IS:%f", percent);
    }
}

/*
 * Method that hidden the progress slider and the progress label after download
 */
- (void) hiddenButtonsAfterDownload {
    
    [self stopNotificationUpdatingFile];
    
        _progressView.hidden = YES;
        _progressLabel.hidden = YES;
        _isViewBlocked = NO;
}


/*
 * This method tell this class to de file is in device
 */
- (void)downloadCompleted:(FileDto *)fileDto {
    DLog(@"Hey, file is in device, go to preview");
    
    if (_typeOfFile == imageFileType) {
        _isUpdatingFile = NO;
    }
   
    //Update fileDto
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    _file = [ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
    
    //Only if the file is the same
     if ([fileDto.localFolder isEqualToString: _file.localFolder]) {
        
        _isDownloading = NO;
        
        _cancelButton.hidden = YES;
        _isFileCharged = YES;
        
        //Update fileDto
        _file=[ManageFilesDB getFileDtoByIdFile:_file.idFile];
        

        //Quit the player if exist
        if (_moviePlayer) {
            [_moviePlayer.moviePlayer stop];
            [_moviePlayer finalizePlayer];
            [_moviePlayer.moviePlayer.view removeFromSuperview];
            _moviePlayer = nil;
        }
        
        //Depend if the file is an image or other "openimage" or "openfile"
        
        if (_file != nil) {
            if (_typeOfFile == officeFileType) {
                [self performSelector:@selector(openFileOffice) withObject:nil afterDelay:0.0];
            } else if(_typeOfFile == audioFileType) {
                [self performSelector:@selector(playMediaFile) withObject:nil afterDelay:0.0];
            } else if(_typeOfFile == videoFileType) {
                [self performSelector:@selector(playMediaFile) withObject:nil afterDelay:0.0];
            }  else if (_typeOfFile == imageFileType){
                DLog(@"Image file");
            } else {
                [self performSelector:@selector(openFile) withObject:nil afterDelay:0.0];
            }
        }
        
        [self performSelector:@selector(hiddenButtonsAfterDownload) withObject:nil afterDelay:0.0];
    }
    //Stop the notification
    [self stopNotificationUpdatingFile];
    //Enable view
    _isViewBlocked = NO;
    [self unBlockFileList];
}

/*
 * This method is for show alert view in main thread.
 */
- (void) showAlertView:(NSString*)string{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:string message:@"" delegate:self cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil];
    [alertView show];
}

/*
 * This method tell this class that exist an error and the file doesn't down to the device
 */
- (void)downloadFailed:(NSString*)string andFile:(FileDto*)fileDto{
    
    _isDownloading = NO;
    
    [self cleanView];
    
    //Enable screen
    _isViewBlocked = NO;
    
    if(string) {
        [self showErrorMessageIfNotIsShowingWithString:string];
    }
    
    [self stopNotificationUpdatingFile];
    
    //Enable screen
    _isViewBlocked = NO;
    [self unBlockFileList];
    [self reloadFileList];
}

- (void) showErrorMessageIfNotIsShowingWithString:(NSString *)string{
    
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    if (!app.downloadErrorAlertView) {
        
        app.downloadErrorAlertView = [[UIAlertView alloc] initWithTitle:string message:@"" delegate:self cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil];
        app.downloadErrorAlertView.tag = k_alertview_for_download_error;
        [app.downloadErrorAlertView show];
    }
    
}

- (void)showNotConnectionWithServerMessage{
    
    [self showErrorMessageIfNotIsShowingWithString:NSLocalizedString(@"not_possible_connect_to_server", nil)];
}

///-----------------------------------
/// @name Update or Cancel the download file
///-----------------------------------

/**
 * This method is called when the download is updating a file
 * and the file has 0 bytes
 *
 * @param download -> id (dynamic type, really is Download class)
 */
- (void)updateOrCancelTheDownload:(id)download{
    
    Download *updatingDownload = (Download*)download;
    
    //UIAlertView with blocks
    [UIAlertView showWithTitle:NSLocalizedString(@"msg_update_file_0_bytes", nil) message:@"" cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:@[NSLocalizedString(@"accept", nil)] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        
        if (buttonIndex == [alertView cancelButtonIndex]) {
            //Cancel
            [updatingDownload cancelDownload];
            [self stopNotificationUpdatingFile];
            
        } else {
            //Update
            [updatingDownload updateDataDownload];
        }
        
    }];
    
}

/*
 * This method is called when the download fail because there are other request on server in progress.
 * Try the download other time
 *
 * This method is not in use yet.
 */
/*- (void)downloadFailedOtherRequestOnServerWithFile:(FileDto*)fileDto{
 
 _isDownloading = NO;
 _file = [ExecuteManager getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:[ExecuteManager getActiveUser]];
 
 if (_file.idFile==fileDto.idFile) {
 DLog(@"Try to download the file other time");
 [_download fileToDownload:fileDto];
 }
 
 
 
 }*/


/*
 * This method receive the string of download progress
 */

- (void)progressString:(NSString*)string andFileDto:(FileDto*)fileDto{
     if ([fileDto.localFolder isEqualToString: _file.localFolder]) {
        [_progressLabel setText:string];
    }
}


- (void)tapCloudButton{
    
    DLog(@"Tap Cloud Button");
}


#pragma mark - Split view support


- (void)splitViewController:(MGSplitViewController*)svc
	 willHideViewController:(UIViewController *)aViewController
		  withBarButtonItem:(UIBarButtonItem*)barButtonItem
	   forPopoverController: (UIPopoverController*)pc
{
	DLog(@"%@", NSStringFromSelector(_cmd));
    DLog(@"Create popover button");
   	
	if (barButtonItem) {
		NSMutableArray *items = [[toolbar items] mutableCopy];
       
        [barButtonItem setImageInsets:UIEdgeInsetsMake(10, 0, -10, 0)];

		[items insertObject:barButtonItem atIndex:0];
		[toolbar setItems:items animated:YES];
	}
    
     pc.popoverBackgroundViewClass=[MainPopOverBarckground class];
  
    //Present popover
    self.popoverController = pc;
}


// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController:(MGSplitViewController*)svc
	 willShowViewController:(UIViewController *)aViewController
  invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
	DLog(@"%@", NSStringFromSelector(_cmd));
	
	if (_isExtend==NO) {
        
        if (barButtonItem) {
            NSMutableArray *items = [[toolbar items] mutableCopy];
            [items removeObject:barButtonItem];
            [toolbar setItems:items animated:YES];
            //[items release];
        }
        self.popoverController = nil;
    }
}


- (void)splitViewController:(MGSplitViewController*)svc
		  popoverController:(UIPopoverController*)pc
  willPresentViewController:(UIViewController *)aViewController {
	DLog(@"%@", NSStringFromSelector(_cmd));
}


- (void)splitViewController:(MGSplitViewController*)svc willChangeSplitOrientationToVertical:(BOOL)isVertical {
	DLog(@"%@", NSStringFromSelector(_cmd));
}


- (void)splitViewController:(MGSplitViewController*)svc willMoveSplitToPosition:(float)position {
	DLog(@"%@", NSStringFromSelector(_cmd));
}


- (float)splitViewController:(MGSplitViewController *)svc constrainSplitPosition:(float)proposedPosition splitViewSize:(CGSize)viewSize {
	DLog(@"%@", NSStringFromSelector(_cmd));
	return proposedPosition;
}


#pragma mark -
#pragma mark Actions

/*
 * MGSplitViewMethod that extend the detail view and
 * configure all of interface objects are in the view.
 */

- (IBAction)toggleMasterView:(id)sender {
    //If is galleryView chraged prepared the scroll view
    if (_galleryView) {
        [_galleryView prepareScrollViewBeforeTheRotation];
    }
    
    [splitController removeThePopover];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        
        //Tell to splitController to extend the detailview
        [splitController toggleMasterView:sender];
        
        
        //Change the global flag
        if (_isExtend==NO) {
            //Set the constraint
            _leftMarginTitleLabelConstraint.constant = 92;
            _isExtend = YES;
        } else {
            //Set the constraint
            _leftMarginTitleLabelConstraint.constant = 62;
            _isExtend = NO;
        }
        
        //Managed the objects of landscape view.
        [self landscapeView];
        
        //If galleryView charged indicated adjust the scroll view
        if (_galleryView) {
            _isExtending = YES;
            [self adjustGalleryScrollView];
        }

        
    });
    
    
}

/*
 * Not used method
 */


- (IBAction)toggleVertical:(id)sender {
	[splitController toggleSplitOrientation:self];
	[self configureView];
}

/*
 * Not used method
 */
- (IBAction)toggleDividerStyle:(id)sender {
	MGSplitViewDividerStyle newStyle = ((splitController.dividerStyle == MGSplitViewDividerStyleThin) ? MGSplitViewDividerStylePaneSplitter : MGSplitViewDividerStyleThin);
	[splitController setDividerStyle:newStyle animated:YES];
	[self configureView];
}

/*
 * Not used method
 */
- (IBAction)toggleMasterBeforeDetail:(id)sender {
	[splitController toggleMasterBeforeDetail:sender];
	[self configureView];
}


#pragma mark -
#pragma mark Rotation support


// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

//Only for ios 6
- (BOOL)shouldAutorotate {
    return YES;
}


- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    
    DLog(@"Will rotate");
    
    if (_galleryView) {
        [_galleryView prepareScrollViewBeforeTheRotation];
    }
    
    if (_mShareFileOrFolder && _mShareFileOrFolder.activityPopoverController) {
        [_mShareFileOrFolder.activityPopoverController dismissPopoverAnimated:NO];
    }
}

-(void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {

    [_mDeleteFile.popupQuery dismissWithClickedButtonIndex:0 animated:YES];

    DLog(@"will Animate Rotation");
    
    //If its in potrait view rotate to landscape view and if the player in full screnn
    //Extend the splitview to see in full screen also in landscape.
    if (_moviePlayer) {
        if (_moviePlayer.isFullScreen) {
            if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
                if (_isExtend==NO) {
                    [self toggleMasterView:nil];
                }
            }
        }
    }
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{

    DLog(@"did rotate");

    [self showPopover];
}

#pragma mark - iOS 8 rotation method.

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    NSTimeInterval duration = 0.5;
    
    // willRotateToInterfaceOrientation code goes here
    [self willRotateToInterfaceOrientation:orientation duration:duration];
    
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        // willAnimateRotationToInterfaceOrientation code goes here
        [self willAnimateRotationToInterfaceOrientation:orientation duration:duration];
        
        
    } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        // didRotateFromInterfaceOrientation goes here (nothing for now)
        [self didRotateFromInterfaceOrientation:orientation];
        
    }];
    
    
    [super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
}

/*
 * Method that tell to galleryView to adjust the scroll view after the rotation
 */
-(void) adjustGalleryScrollView {
    
    [self configureView];
    
    if (_galleryView) {
        [_galleryView.scrollView setFrame:_mainScrollView.frame];
        [_galleryView adjustTheScrollViewAfterTheRotation];
    }
}



#pragma mark - Error login delegate method

- (void)errorLogin {
    
    if (_updatingFileView) {
        [self stopNotificationUpdatingFile];
    }
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate.downloadManager errorLogin];
    
    
    DLog(@"Error login");
    
    if(k_is_oauth_active) {
        NSURL *url = [NSURL URLWithString:k_oauth_login];
        [[UIApplication sharedApplication] openURL:url];
    } else {
        
        //Flag to indicate that the error login is in the screen
        if (appDelegate.isErrorLoginShown==NO) {
            appDelegate.isErrorLoginShown=YES;
            
            //In SAML the error message is about the session expired
            if (k_is_sso_active) {
                [self performSelectorOnMainThread:@selector(showAlertView:)
                                       withObject:NSLocalizedString(@"session_expired", nil)
                                    waitUntilDone:YES];
            } else {
                [self performSelectorOnMainThread:@selector(showAlertView:)
                                       withObject:NSLocalizedString(@"error_login_message", nil)
                                    waitUntilDone:YES];
            }
            
            EditAccountViewController *viewController = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:appDelegate.activeUser];
            [viewController setBarForCancelForLoadingFromModal];
            
            
            if (IS_IPHONE) {
                OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController];
                [self.navigationController presentViewController:navController animated:YES completion:nil];
            } else {
                
                if (IS_IOS8) {
                    [self.popoverController dismissPopoverAnimated:YES];
                }
                
                OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController];
                navController.modalPresentationStyle = UIModalPresentationFormSheet;
                [appDelegate.splitViewController presentViewController:navController animated:YES completion:nil];
            }
        }
    }
}

#pragma mark - Notifications methods

/*
 * This method addObservers for notifications to this class.
 * The notifications added in viewDidLoad
 */

- (void) setNotificationForCommunicationBetweenViews {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePreviewOverwriteFile:) name:PreviewFileNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePreviewFileWithNewIDFromDB:) name:uploadOverwriteFileNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updatePreviewFileWithNewIdFromDBWhenAFileISDelete:) name:fileDeleteInAOverwriteProcess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cleanView) name:IpadCleanPreviewNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNotConnectionWithServerMessage) name:IpadShowNotConnectionWithServerMessageNotification object:nil];
}


/*
 *Method that checks if the preview file is the same that the file that is contained in the notification object and updates the preview file view if the overwrite file was previewed
 */
-(void)updatePreviewOverwriteFile:(NSNotification *)notification{
    
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    //Update the _file with DB
    _file=[ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
    
    NSString *path = (NSString*)[notification object];
    NSString *pathPreview=[UtilsDtos getRemoteUrlByFile:_file andUserDto:app.activeUser];
    
    if ([path isEqualToString:pathPreview]) {
        DLog(@"The file is the same, update the preview");
        _file.isDownload=downloaded;
        _isOverwritedFile = YES;
        [self handleFile:_file fromController:_controllerManager];
        DLog(@"id file: %d",_file.idFile);
    }    
}



- (void) receiveTestNotification:(NSNotification *) notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        int messageTotal = [[userInfo objectForKey:@"total"] intValue];
        NSLog (@"Successfully received test notification! %i", messageTotal);
    }
}

/*
 *Method that update the preview file with the correct id from DB
 */
-(void)updatePreviewFileWithNewIDFromDB:(NSNotification *)notification{
    DLog(@"updatePreviewFileWithNewIDFromDB");
    
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    //Update the preview file with the new information in DB
    _file=[ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
    app.isOverwriteProcess = NO;
}


/*
 *Method that update the preview file with the correct id from DB when a file in a upload process is cancel
 */
-(void)updatePreviewFileWithNewIdFromDBWhenAFileISDelete:(NSNotification *)notification{
    DLog(@"updatePreviewFileWithNewIdFromDBWhenAFileISDelete");
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    //Update the file with the new information in DB
    _file=[ManageFilesDB getFileDtoByFileName:_file.fileName andFilePath:[UtilsDtos getFilePathOnDBFromFilePathOnFileDto:_file.filePath] andUser:app.activeUser];
    DLog(@"file id: %d",_file.idFile);
    
    NSString *path = (NSString*)[notification object];
    NSString * pathPreview=[UtilsDtos getRemoteUrlByFile:_file andUserDto:app.activeUser];
    
    //If the cancel file is the same that the previewed file, clean the view
    if ([path isEqualToString:pathPreview]) {
        [app.detailViewController presentWhiteView];
    }
}



///-----------------------------------
/// @name Show a text in the status bar
///-----------------------------------

/**
 * This method shows a text in the status bar of the device
 */
- (void) showTextInStatusBar {
    
    if (_isDownloading && _updatingFileView.hidden == NO && nameFileToUpdate == _file.fileName) {
        DLog(@"Show a notification text in the status bar");
        //Notificacion style
        _notification.notificationLabelBackgroundColor = [UIColor whiteColor];
        _notification.notificationLabelTextColor = [UIColor colorOfNavigationBar];
        _notification.notificationAnimationInStyle = CWNotificationAnimationStyleTop;
        _notification.notificationAnimationOutStyle = CWNotificationAnimationStyleTop;
        //File name
        NSString *notificationText = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"updating", nil), [nameFileToUpdate stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        DLog(@"name: %@",notificationText);
        [_notification displayNotificationWithMessage:notificationText completion:nil];
    }
}




///-----------------------------------
/// @name Stop notification in status bar
///-----------------------------------

/**
 * This method removes the notification in the status bar
 * and put the name of the file in the title of the navigation bar
 */
- (void) stopNotificationUpdatingFile {
    DLog(@"Stop the notification in the status bar");
    [_notification dismissNotification];
    _updatingFileView.hidden = YES;
    _titleLabel.hidden = NO;
}




#pragma mark - Loading Methods

/*
 * Add loading screen and block the view
 */
- (void) initLoading {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hud bringSubviewToFront:self.view];
    
    hud.labelText = NSLocalizedString(@"loading", nil);
    hud.dimBackground = NO;
    
    self.view.userInteractionEnabled = NO;
    self.navigationController.navigationBar.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}

- (void) endLoading {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    self.view.userInteractionEnabled = YES;
    self.navigationController.navigationBar.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

#pragma mark - UIAlertView delegate methods

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (alertView.tag) {
        case k_alertview_for_download_error: {
            
            AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
            app.downloadErrorAlertView = nil;
            
            break;
        }
        default:
            break;
    }
}

@end
